#include "lv_port_indev.h"
#include "driver/gpio.h"
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>

#define KEY_UP    5
#define KEY_DOWN  9
#define KEY_LEFT  8
#define KEY_RIGHT 13
#define KEY_MID   4

lv_indev_t* indev_keypad;

static void keypad_init()
{
	gpio_reset_pin(KEY_UP);
	gpio_set_direction(KEY_UP, GPIO_MODE_INPUT);

	gpio_reset_pin(KEY_DOWN);
	gpio_set_direction(KEY_DOWN, GPIO_MODE_INPUT);

	gpio_reset_pin(KEY_LEFT);
	gpio_set_direction(KEY_LEFT, GPIO_MODE_INPUT);

	gpio_reset_pin(KEY_RIGHT);
	gpio_set_direction(KEY_RIGHT, GPIO_MODE_INPUT);

	gpio_reset_pin(KEY_MID);
	gpio_set_direction(KEY_MID, GPIO_MODE_INPUT);
}

static uint32_t keypad_get_key(void)
{
	if(0 == gpio_get_level(KEY_DOWN)) {
		return 1;
	} else if(0 == gpio_get_level(KEY_UP)) {
		return 2;
	} else if(0 == gpio_get_level(KEY_LEFT)) {
		return 3;
	} else if(0 == gpio_get_level(KEY_RIGHT)) {
		return 4;
	} else if(0 == gpio_get_level(KEY_MID)) {
		return 5;
	}

	return 0;
}

/*Will be called by the library to read the mouse*/
static void keypad_read(lv_indev_drv_t* indev_drv, lv_indev_data_t* data)
{
	static uint32_t last_key = 0;

	uint32_t act_key = keypad_get_key();
	if (act_key != 0) {
		data->state = LV_INDEV_STATE_PR;

		switch (act_key) {
		case 1:
			act_key = LV_KEY_NEXT;
			break;
		case 2:
			act_key = LV_KEY_PREV;
			break;
		case 3:
			act_key = LV_KEY_LEFT;
			break;
		case 4:
			act_key = LV_KEY_RIGHT;
			break;
		case 5:
			act_key = LV_KEY_ENTER;
			break;
		}

		last_key = act_key;
	} else {
		data->state = LV_INDEV_STATE_REL;
	}

	data->key = last_key;
}

void lv_port_indev_init(void)
{
	static lv_indev_drv_t indev_drv;

	keypad_init();

	lv_indev_drv_init(&indev_drv);
	indev_drv.type = LV_INDEV_TYPE_KEYPAD;
	indev_drv.read_cb = keypad_read;
	indev_keypad = lv_indev_drv_register(&indev_drv);

	lv_group_t* group = lv_group_get_default();
	if (!group) {
		group = lv_group_create();
		lv_group_set_default(group);
	}

	lv_indev_set_group(indev_keypad, group);
}

